/**
 * @(#)ServerHandler.java, Sep 13, 2012. 
 * 
 * Copyright 2012 Yodao, Inc. All rights reserved.
 * YODAO PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.buaaer.mina;

import java.lang.reflect.Method;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

/**
 *
 * @author wangheng
 *
 */
public class ServerHandler extends IoHandlerAdapter {
    
    private Object instance;
    
    public ServerHandler(Object instance) {
        this.instance = instance;
    }
    
    public void sessionCreated(IoSession session) throws Exception {
        System.out.println(session.getId() + " created");
    }
 
    public void sessionOpened(IoSession session) throws Exception {
        System.out.println(session.getId() + " opened");
    }
    
    public void sessionClosed(IoSession session) throws Exception {
        System.out.println(session.getId() + " closed");
    }
    
    public void messageReceived(IoSession session, Object message)
            throws Exception {
        System.out.print("recv:");
        DataPackage data = (DataPackage)message;
        CallBody call = (CallBody)data.getObject();
        
        Method method = instance.getClass().getMethod(call.getMethodName(), call.getParamTypes());
        
//        Class<?> clazz =  Class.forName(call.getClassName());
//        Constructor<?> constructor = clazz.getConstructor();
//        Object instance = constructor.newInstance();
//        
//        Method method = clazz.getMethod(call.getMethodName(), call.getParamTypes());
//        
        Object result = method.invoke(instance, call.getParamValues());
        
        System.out.println("result:" + result);
        
        data.setObject(result);
        
        session.write(data);
    }
}
